/**
  ******************************************************************************
  * @file    lscm_usart_1.c
  * @author  Andrew Yeung
  * @version 1.0
  * @date    
  * @brief   
  ******************************************************************************
  */

#include "lscm_usart.h"
#include "lscm_usart_1.h"

T_USART_Buffer usart1;
extern UART_HandleTypeDef huart1;


int lscm_usart1_init (void)
{
    int result = 0;
    result += lscm_usart1_reset_buffer ();
    HAL_UART_Receive_DMA(&huart1, &usart1.rx_data, USART1_DMA_IRQ_TRI);
    return result;
}

int lscm_usart1_reset_buffer (void)
{
    for (int i=0; i<USART_RX_BUF_SIZE; i++)
    {
        usart1.rx_buffer[i] = 0x00;
    }
    usart1.rx_index = 0;
    
    if (usart1.rx_buffer[0] == 0x00)
    {
        return 1;
    }
    else
    {
        return -1;
    }
}

int lscm_usart1_enqueue_data_to_buffer (uint8_t data)
{
    usart1.rx_buffer[usart1.rx_index++] = data;
    if (usart1.rx_index > USART_RX_BUF_SIZE)
    {
        usart1.rx_index = 0;
        return 0;
    }
    
    return 1;
}


void lscm_usart1_printf (const char* format,...)
{
    uint32_t length;
    va_list args;
    va_start(args, format);
    length = vsnprintf((char *)usart1.tx_buffer, sizeof(usart1.tx_buffer), (char *)format, args);
    va_end(args);

    for (int i=0; i<length; i++)
    {
        HAL_UART_Transmit(&huart1, (uint8_t *)&usart1.tx_buffer[i], 1, 10);
    }
}

void lscm_usart1_printf_dma (const char* format,...)
{
    uint32_t length;
    va_list args;
    va_start(args, format);
    length = vsnprintf((char *)usart1.tx_buffer, sizeof(usart1.tx_buffer), (char *)format, args);
    va_end(args);

    HAL_UART_Transmit_DMA(&huart1, (uint8_t *)usart1.tx_buffer, length);
}

